import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'

declare global {
  interface Window {
    __ZJCAAllJsErrorPatched?: boolean
  }
}

const shouldIgnoreZjcaSdkError = (message?: string, source?: string) => {
  if (!message) return false
  const isUndefinedReadError = message.includes("Cannot read properties of undefined (reading '0')")
  const isZjcaBundle = source?.includes('all.js')
  return isUndefinedReadError && (!!source ? isZjcaBundle : true)
}

const swallowZjcaErrorEvent = (event: ErrorEvent) => {
  if (!event) return false
  if (shouldIgnoreZjcaSdkError(event.message, event.filename)) {
    event.preventDefault()
    event.stopImmediatePropagation()
    return true
  }
  return false
}

if (typeof window !== 'undefined' && !window.__ZJCAAllJsErrorPatched) {
  window.__ZJCAAllJsErrorPatched = true

  window.addEventListener(
    'error',
    (event) => {
      swallowZjcaErrorEvent(event)
    },
    true,
  )

  const previousOnError = window.onerror
  window.onerror = (message, source, lineno, colno, error) => {
    const normalizedMessage =
      typeof message === 'string'
        ? message
        : (message as ErrorEvent | undefined)?.message || error?.message || ''
    const normalizedSource =
      typeof source === 'string'
        ? source
        : (message as ErrorEvent | undefined)?.filename || (error as any)?.fileName || undefined

    if (shouldIgnoreZjcaSdkError(normalizedMessage, normalizedSource)) {
      return true
    }

    if (typeof previousOnError === 'function') {
      const result = previousOnError(message, source, lineno, colno, error)
      return result === true
    }

    return false
  }
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
